package com.hcb.app911;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import com.hcb.adapter.AdapterListPhoneNumber;
import com.hcb.dto.ContactsDTO;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ListPhoneNumberActivity extends FragmentActivity implements
		OnItemClickListener {
	ListView lvphonenumber;
	AdapterListPhoneNumber adapter;

	ArrayList<Object> arrData;
	Button btnyes, btnno;

	Dialog dialog;
	// LinearLayout header;
	EditText edSearchName;

	@SuppressLint("ServiceCast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_phone_number);

		edSearchName = (EditText) findViewById(R.id.edSearchName);
		// edSearchName.setInputType(0);
		// header = (LinearLayout) findViewById(R.id.header);
		//
		// header.setVisibility(View.GONE);

		newArr = getListContact();
		arrData = new ArrayList<Object>();

		adapter = new AdapterListPhoneNumber(this,
				R.layout.adapter_list_phone_number, arrData);
		lvphonenumber = (ListView) findViewById(R.id.lvphonenumber);

		lvphonenumber.setAdapter(adapter);

		Collections.sort(arrData, objComparator);
		new VerySlowTask(newArr).execute();
		// initPhoneNumber();
		// if (arrData.size() == 0) {
		//
		// dialog = new Dialog(ListPhoneNumberActivity.this,
		// android.R.style.Theme_Translucent);
		// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//
		// dialog.setCancelable(true);
		// dialog.setContentView(R.layout.already_dialog);
		// btnyes = (Button) dialog.findViewById(R.id.btnyes);
		// btnno = (Button) dialog.findViewById(R.id.btnno);
		// TextView txtNamedialog = (TextView) dialog
		// .findViewById(R.id.txtNamedialog);
		// txtNamedialog
		// .setText("don't find contacts, do you want add contact");
		//
		// btnyes.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// header.setVisibility(View.VISIBLE);
		// btnAddcontacts.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// String name = edusername.getText().toString();
		// String phoneNumber = edphonenumber.getText()
		// .toString();
		// if (arrData.size() == 2) {
		// header.setVisibility(View.GONE);
		// } else {
		//
		// if (!name.equalsIgnoreCase("")
		// && !phoneNumber.equalsIgnoreCase("")) {
		// if (isValidInput(phoneNumber)) {
		// ContactsDTO dto = new ContactsDTO();
		// dto.setName(name);
		// dto.setNumber(phoneNumber);
		// Intent intent = new Intent();
		// Bundle bundle = new Bundle();
		// bundle.putSerializable("myobj", dto);
		// intent.putExtras(bundle);
		// setResult(Activity.RESULT_OK, intent);
		// finish();
		// }
		//
		// // arrData.add(dto);
		// //
		// //
		// // finish();
		// //
		// // adapter.notifyDataSetChanged();
		// // if (arrData.size() == 2) {
		// // header.setVisibility(View.GONE);
		// // }
		//
		// } else {
		// Toast.makeText(
		// ListPhoneNumberActivity.this,
		// "please input all values",
		// Toast.LENGTH_LONG).show();
		// }
		// edusername.setText("");
		// edphonenumber.setText("");
		// }
		//
		// }
		// });
		// dialog.dismiss();
		// }
		// });
		// btnno.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// dialog.dismiss();
		// finish();
		//
		// }
		// });
		//
		// dialog.show();
		// }
		lvphonenumber.setOnItemClickListener(this);

		edSearchName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!newArr.contains(null)) {
					String text = edSearchName.getText().toString()
							.toLowerCase(Locale.getDefault());
					filter(text);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	ArrayList<ContactsDTO> newArr;

	public void filter(String charText) {
		charText = charText.toLowerCase(Locale.getDefault());
		arrData.clear();
		if (charText.length() == 0) {
			arrData.addAll(newArr);
			adapter.notifyDataSetChanged();
		} else {
			for (ContactsDTO contacts : newArr) {
				if (contacts.getName().toLowerCase(Locale.getDefault())
						.contains(charText)) {
					arrData.add(contacts);
					adapter.notifyDataSetChanged();
				}
			}
		}

	}

	public class VerySlowTask extends AsyncTask<String, Object, Void> {

		List<ContactsDTO> _newArr;

		public VerySlowTask(List<ContactsDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					publishProgress(_newArr.get(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (arrData.size() == 0) {
				dialog = new Dialog(ListPhoneNumberActivity.this,
						android.R.style.Theme_Translucent);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

				dialog.setCancelable(true);
				dialog.setContentView(R.layout.dialog_dont_find);
				Button btnExit = (Button) dialog.findViewById(R.id.btnExit);

				TextView txtNamedialog = (TextView) dialog
						.findViewById(R.id.txtNamedialog);
				txtNamedialog.setText("don't find contacts");
				btnExit.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						dialog.dismiss();
						finish();

					}
				});
				dialog.show();
			}

			Collections.sort(arrData, objComparator);
			adapter.notifyDataSetChanged();

		}

	}

	public ArrayList<ContactsDTO> getListContact() {
		ArrayList<ContactsDTO> arr = new ArrayList<ContactsDTO>();
		Cursor phones = getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		while (phones.moveToNext()) {
			ContactsDTO dto = new ContactsDTO();
			dto.setName(phones.getString(phones
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
			dto.setNumber(phones.getString(phones
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
			arr.add(dto);
			// newArr.add(dto);
		}
		return arr;
	}

	public void initPhoneNumber() {
		newArr = new ArrayList<ContactsDTO>();
		Cursor phones = getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		while (phones.moveToNext()) {
			ContactsDTO dto = new ContactsDTO();
			dto.setName(phones.getString(phones
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
			dto.setNumber(phones.getString(phones
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
			arrData.add(dto);
			newArr.add(dto);
		}

		phones.close();
	}

	Comparator<Object> objComparator = new Comparator<Object>() {
		public int compare(Object o1, Object o2) {
			ContactsDTO dto = (ContactsDTO) o1;
			String str1 = dto.getName();
			ContactsDTO dto2 = (ContactsDTO) o2;
			String str2 = dto2.getName();
			return str1.compareTo(str2);
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		Intent intent = new Intent();
		ContactsDTO dto = (ContactsDTO) lvphonenumber
				.getItemAtPosition(position);
		Bundle bundle = new Bundle();
		bundle.putSerializable("myobj", dto);
		intent.putExtras(bundle);
		setResult(Activity.RESULT_OK, intent);
		finish();

	}
}
